import { combineReducers } from 'redux';
import { Actions } from '../../../core/utils/IConstant';

function selectedTabIndexReducer(state = 0, action)
{
    switch(action.type)
    {
    case Actions.NEWS.LIST.SET_SELECTED_TAB_INDEX:
        return action.index;
    case Actions.NEWS.LIST.GO_BACK:
        return 0;
    default:
        return state;
    }
}

function groupReducer(state = {}, action)
{
    let obj = state[action.key];
    obj = obj ? obj : {};
    switch(action.type)
    {
    case Actions.NEWS.LIST.GET_LIST_REQUEST:
        return {
            ...state, 
            [action.key]: {
                ...obj,
                isFetching: true,
                pageIndex: action.pageIndex,
            }
        };
    case Actions.NEWS.LIST.GET_LIST_SUCCESS:
        let dataList = action.pageIndex === 1 ? [] : obj.dataList;
        dataList = dataList ? dataList : [];
        if(action.result.results)
        {
            dataList = dataList.concat(action.result.results);
        }
        return {
            ...state,
            [action.key]: {
                ...obj,
                isFetching: false,
                dataList: dataList,
                total: action.result.total,
                pageIndex: action.pageIndex,
                hasMore: (action.result.total > dataList.length)
            }
        };
    case Actions.NEWS.LIST.GET_LIST_FAILURE:
        return {
            ...state,
            [action.key]: {
                ...obj,
                isFetching: false,
            }
        };
    case Actions.NEWS.LIST.GO_BACK:
        return {};
    case Actions.NEWS.LIST.DELETE:
        return {
            ...state,
            [action.key]: {
                isFetching: false,
                dataList: [],
            }
        };
    case Actions.NEWS.LIST.SET_LISTVIEW_OFFSET:
        return {
            ...state, 
            [action.key]: {
                ...obj,
                listViewOffset: action.listViewOffset
            }
        };
    case Actions.NEWS.LIST.INCREASE_CLICK_COUNT:
        {
            let dataList = action.pageIndex === 1 ? [] : obj.dataList;
            dataList = dataList ? dataList : [];
            for(let i = 0; i < dataList.length; i++)
            {
                let item = dataList[i];
                if(item.ContentCode === action.code)
                {
                    if(!isNaN(item.ClickCount))
                    {
                        item.ClickCount = item.ClickCount + 1;
                    }
                    break;
                }
            }
            obj.dataList = [...dataList];
        }
        return {
            ...state, 
            [action.key]: {
                ...obj,
            }
        };
    default:
        return state;
    }
}

const listReducer = combineReducers({
    selectedTabIndex: selectedTabIndexReducer,
    groups: groupReducer,
});

export default listReducer;